// pages/storedValue/storedValue.js
import {
  postRequest,
  getRequest,
  postParamsRequest
} from '../../api/request'
import {
  showToast,
  trim
} from '../../utils/util';
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    themeColor: app.globalData.themeColor,
    subColor: app.globalData.subColor,
    btnColor: app.globalData.btnColor,
    openVip: 1, //是否开启vip业务
    openVipCard: 1, //是否激活会员卡:1-是，0-否
    //vip信息
    vipInfo: {
      mobile: "",
      openApply: 0
    },
    //激活弹窗
    isShow: false,
    //充值类型0为自定义充值，1，2，4，设置充值
    type: 0,
    //是否自定义金额
    customizeRecharge: 0,
    //自定义金额
    customizeValue: "",
    //会员充值配置
    rechargeDiscountRule: [],
    //账号余额
    cardRemaining: "0.00",
    //储值金额
    rechargePrice: 0,
    //你将获得
    useMessage: '',
    //使用说明
    explain: '',
    //是否冻结储值按钮
    isRechargePay: false,
    //提交锁
    submitLock: false,
    submitLock2: false,
    //等待加载
    loadModal: false,
    showStyle: 0,
    tmplIds: [], //模板
  },

  //充值类型改变时
  onStoredChange(e) {
    console.log(e.currentTarget.dataset.explain);
    this.setData({
      type: e.currentTarget.dataset.type,
      useMessage: e.currentTarget.dataset.desc,
      explain: e.currentTarget.dataset.explain,
    });
  },

  //自定义金额聚焦时
  onStoredFocus(e) {
    this.setData({
      type: e.currentTarget.dataset.type,
      useMessage: "自定义充值的金额",
      explain: "1：可在购买商品时使用",
    });
  },
  //自定义金额改变时
  changeMoney(e) {
    this.setData({
      customizeValue: Number(e.detail.value).toFixed(2),
    })
  },
  //前往交易记录页
  toRechargeOrderListPage() {
    wx.navigateTo({
      url: '../rechargeOrderList/rechargeOrderList',
    })
  },
  //关闭激活弹窗
  closeModel() {
    this.setData({
      isShow: false
    })
  },
  //打开激活弹窗
  openModel() {
    this.setData({
      isShow: true
    })
  },
  //获取手机号
  getPhoneNumber(e) {
    console.log(e);
    if (e.detail.errMsg != 'getPhoneNumber:ok') {
      return
    }
    let param = {
      iv: e.detail.iv,
      encryptedData: e.detail.encryptedData,
      memberId: app.myInfo.memberId,
    };
    postParamsRequest("/api/vip/getPhoneNumber", param).then((res) => {
      console.log(res);
      let data = res.data.data
      if (data.phoneNumber) {
        this.setData({
          'vipInfo.mobile': data.phoneNumber,
        });
      }
    }).catch((err) => {});
  },
  //立即激活
  formSubmit(e) {
    let mobile = trim(e.detail.value.mobile);

    if (mobile == "") {
      wx.showToast({
        title: '手机号不能为空',
        icon: 'none'
      })
      return;
    }

    let param = {
      memberId: app.myInfo.memberId,
      mobile: mobile,
    };

    this.setData({
      submitLock2: true,
    })
    postParamsRequest("/api/vip/activate", param).then((res) => {
      console.log(res);
      this.setData({
        submitLock2: false
      })
      //获取会员配置
      this.getMemberConfig();
    }).catch((err) => {
      this.setData({
        submitLock2: false
      })
    });

  },
  //点击立即储值
  rechargePay() {
    //获取充值金额
    if (this.data.type == 0) {
      this.setData({
        rechargePrice: this.data.customizeValue,
      });
    } else {
      this.setData({
        rechargePrice: this.data.rechargeDiscountRule[this.data.type - 1].recharge,
      });
    }
    this.recharge(this, this.data.rechargePrice);
  },
  //获取订阅信息
  getSubscriptionMessageTplIds() {
    let that = this;
    //会员余额消费通知
    getRequest("/api/msg/getSubscriptionMessageTplIds", {
      msgType: '21'
    }).then((_res) => {
      console.log(_res.data.data);
      if (_res.data.data.length > 0) {
        let setList = []
        wx.getSetting({
          withSubscriptions: true,
          success(setRes) {
            console.log(setRes);
            if (setRes.subscriptionsSetting) {
              setList = Object.keys(setRes.subscriptionsSetting)
            }
            let tmplIds = []
            _res.data.data.forEach(element => {
              if (setList.indexOf(element) == -1) {
                tmplIds.push(element)
              }
            });
            that.setData({
              tmplIds: tmplIds
            })
          },
          fail() {}
        })
      } else {}
    }).catch((err) => {

    });
  },

  //储值
  recharge(self, price) {
    if (self.data.submitLock) {
      return;
    }
    if (this.data.type == 0 && this.data.customizeRecharge == 0) {
      showToast("请选择充值金额");
      return;
    }
    if (price == undefined || price <= 0) {
      showToast("充值金额不正确");
      return;
    }
    self.setData({
      submitLock: true
    })
    postParamsRequest("/api/vip/member/createRechargeOrder", {
      memberId: app.myInfo.memberId,
      price: trim(price),
    }).then((res) => {
      console.log(res.data.data);
      postParamsRequest("/api/vip/member/payRechargeOrder", {
        orderId: res.data.data.orderId,
      }).then((res) => {
        console.log(res.data.data);
        self.setData({
          submitLock: false
        })
        let data = res.data.data
        wx.requestPayment({
          'timeStamp': data.timeStamp,
          'nonceStr': data.nonceStr,
          'package': data.package,
          'signType': data.signType,
          'paySign': data.paySign,
          'success': function (res) {
            console.log(res);

            //初始化金额
            self.setData({
              rechargePrice: 0,
              customizeValue: ""
            });

            self.setData({
              loadModal: true,
            });
            setTimeout(() => {
              self.getCardRemaining();
              self.setData({
                loadModal: false
              })
              wx.showModal({
                title: '提示',
                content: '充值成功',
                showCancel: false,
                success(res) {
                  if (res.confirm) {
                    //订阅信息
                    let tmplIds = self.data.tmplIds;
                    if (tmplIds.length > 0) {
                      //没有订阅权限唤起窗口
                      if (wx.requestSubscribeMessage) {
                        wx.requestSubscribeMessage({
                          tmplIds: tmplIds,
                          success(_res) {},
                          complete(_res) {}
                        })
                      }
                    }
                  }
                }
              })

            }, 1000)
          },
          'fail': function (res) {
            self.setData({
              submitLock: false,
            })
            showToast("充值失败");
          }
        })
      }).catch((err) => {
        self.setData({
          submitLock: false
        })
      });
    }).catch((err) => {
      self.setData({
        submitLock: false
      })
    });
  },
  //获取账号金额
  getCardRemaining() {
    let that = this;
    //获取账号余额
    getRequest("/api/vip/getUserBaseInfo", {
      memberId: app.myInfo.memberId
    }).then((res) => {
      console.log(res.data.data);
      if (res.data.data != null) {
        that.setData({
          cardRemaining: res.data.data.cardRemaining,
          openVipCard: res.data.data.openVipCard,
          isShow: res.data.data.openVipCard == 0,
          showStyle: 1,
        })
        // 停止下拉刷新效果
        wx.stopPullDownRefresh()
      }
    }).catch((err) => {
      that.setData({
        showStyle: 3,
      })
      // 停止下拉刷新效果
      wx.stopPullDownRefresh()
    });
  },
  //获取会员配置
  getMemberConfig() {
    let that = this;
    wx.showLoading({
      title: "加载中..."
    });
    getRequest("/api/vip/member/config", {}).then((res) => {
      console.log(res.data.data);
      if (res.data.data != null) {
        //如果开通了会员业务显示
        if (res.data.data.openVip == 1) {
          //获取账号余额
          that.getCardRemaining()
        }

        let rule = res.data.data.rechargeDiscountRule == '' ? [] : JSON.parse(res.data.data.rechargeDiscountRule);
        let isRechargePay = false;
        //判断，有自定义金额和充值优惠时才可充值
        if (res.data.data.customizeRecharge == 1 || rule.length > 0) {
          isRechargePay = true;
        }
        if (res.data.data.customizeRecharge == 1) {
          this.setData({
            useMessage: "自定义充值的金额",
            explain: "1：可在购买商品时使用",
          });
        }
        that.setData({
          customizeRecharge: res.data.data.customizeRecharge,
          rechargeDiscountRule: rule,
          isRechargePay: isRechargePay,
          openVip: res.data.data.openVip,
        });
      } else {
        that.setData({
          showStyle: 1,
          openVip: 0,
        })
      }
      console.log(that.data);
      wx.hideLoading();
    }).catch((err) => {});
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    let that = this;
    //如果没有token,则需要重新登录获取个人信息等，避免缺少id导致数据无法获取
    if (app.token == "" || app.token == undefined) {
      app.initLogin().then(res => {
        that.getSubscriptionMessageTplIds();
        //获取会员配置
        that.getMemberConfig();
      }).catch(err => {})
    } else {
      that.getSubscriptionMessageTplIds();
      //获取会员配置
      that.getMemberConfig();
    }

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    //获取会员配置
    this.getMemberConfig();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})